package com.github.data_manage.util

import com.fasterxml.jackson.core.JsonGenerator
import com.fasterxml.jackson.core.JsonParser
import com.fasterxml.jackson.core.JsonProcessingException
import com.fasterxml.jackson.core.TreeNode
import com.fasterxml.jackson.databind.DeserializationContext
import com.fasterxml.jackson.databind.JsonDeserializer
import com.fasterxml.jackson.databind.JsonSerializer
import com.fasterxml.jackson.databind.SerializerProvider
import com.fasterxml.jackson.databind.node.ArrayNode
import org.springframework.util.StringUtils
import java.io.IOException
import java.util.function.IntFunction
import java.util.stream.Collectors
import java.util.stream.IntStream

class StringToArraySerialize : JsonSerializer<String?>() {

    @Throws(IOException::class)
    override fun serialize(value: String?, gen: JsonGenerator, serializers: SerializerProvider?) {
        if (StringUtils.hasText(value)) {
            val strings: Array<String?> =
                value!!.replace("\"".toRegex(), "").split(",".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
            gen.writeArray(strings, 0, strings.size)
        } else {
            gen.writeObject(mutableListOf<Any?>())
        }
    }
}

class ArrayToStringDeSerialize : JsonDeserializer<String?>() {
    @Throws(IOException::class, JsonProcessingException::class)
    override fun deserialize(parser: JsonParser, context: DeserializationContext?): String {
        val treeNode = parser.codec.readTree<TreeNode?>(parser) ?: return ""
        if (treeNode.isArray && treeNode is ArrayNode) {
            return IntStream.range(0, treeNode.size())
                .mapToObj<String?>(IntFunction { i: Int -> treeNode.get(i).toString().replace("\"".toRegex(), "") })
                .collect(Collectors.joining(","))
        }
        return ""
    }
}


//class ObjectToStringDeSerialize : JsonSerializer<Any?>() {
//
//}